package com.mlog.njyjy.ndop.msg.relay.task;

import cn.hutool.core.util.StrUtil;
import com.mlog.njyjy.ndop.msg.common.domain.ItemStats;
import com.mlog.njyjy.ndop.msg.common.support.DateTimeUtil;
import com.mlog.njyjy.ndop.msg.persistence.dao.ItemStatsRepository;
import com.mlog.njyjy.ndop.msg.relay.util.Constant;
import com.mlog.njyjy.ndop.share.sql.support.SqlTableUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @program: NMC-DevOps-Platform
 * @description: ${description} 统计
 * @author: socker
 * @create: 2020-07-22 09:34
 */

@Slf4j
@Component
@EnableScheduling
public class CountTask extends BaseTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ItemStatsRepository msgStatsRepository;


    @Override
    @Scheduled(cron = "0 0/10 * * * ?")
    public void startJob() {
        startJobWithCheckStatus(() -> run());
    }


    protected void doJob() {

        String now = DateTimeUtil.format(LocalDateTime.now(), "yyyyMMdd");
        String processKey = Constant.PROCESS + now;
        String errorKey = Constant.ERROR + now;
        String failKey = Constant.VALIDATE_FAIL + now;

        int processCnt = redisTemplate.opsForSet().size(processKey).intValue();
        int errorCnt = redisTemplate.opsForSet().size(errorKey).intValue();
        int failCnt = redisTemplate.opsForSet().size(failKey).intValue();
        int totalCnt = processCnt + errorCnt + failCnt;
        List<ItemStats> list = msgStatsRepository.find(StrUtil.format("select id from {} where time = ? ",
                SqlTableUtil.getTblName(ItemStats.class)), now);
        if (list == null || list.isEmpty()) {
            msgStatsRepository.insert(new ItemStats().setStatsAllMsg(totalCnt).setStatsErrorMsg(errorCnt)
                    .setStatsFailMsg(failCnt).setStatsSuccessMsg(processCnt).setTime(now));
        } else {
            msgStatsRepository.update(new ItemStats().setId(list.get(0).getId()).setStatsAllMsg(totalCnt).setStatsErrorMsg(errorCnt)
                    .setStatsFailMsg(failCnt).setStatsSuccessMsg(processCnt).setTime(now));
        }

        log.info(" 统计当天时间成功/失败的统计和完成。");
    }
}